import { reqShopCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api";
const state = {
    cartList: []
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
};
const actions = {
    async getCartList({ commit }) {
        let result = await reqShopCartList()
        if (result.code == 200) {
            commit('GETCARTLIST', result.data)
        }
    },
    async deleteCart({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code == 200) {
            return 'success'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return 'success'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //删除全选的产品
    deleteAllCheckCart({ getters, dispatch }) {
        //context:上下文 里面有很多东西按需解构getters dispatch
        //获取购物车中全部的产品
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCart', item.skuId) : ''
            //将每次返回的promise添加到数组中
            PromiseAll.push(promise)
        });
        //只要全部的promise全都成功 返回的结果即为成功
        return Promise.all(PromiseAll)
    },
    //修改全部产品的勾选状态
    updateAllCheck({ dispatch, state }, isChecked) {
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }

};
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
};

export default {
    state,
    mutations,
    actions,
    getters
}